package com.zhhtech.zhh.ui.helper

import androidx.lifecycle.LifecycleOwner
import com.zhhtech.zhh.ui.ext.DefaultLifecycleObserver

typealias OnForegroundChange = (isForeground: Boolean) -> Unit

/**
 * 监听App是否被其他app覆盖或者回退到桌面
 */
object ProcessLifecycleObserver : DefaultLifecycleObserver {
    var isForeground: Boolean = true
    internal val foregroundChange: MutableList<ForegroundLifecycleObserver> = mutableListOf()
    override fun onStart(owner: LifecycleOwner) {
        isForeground = true
        notifyForegroundChange()
    }

    override fun onStop(owner: LifecycleOwner) {
        isForeground = false
        notifyForegroundChange()
    }

    fun observe(owner: LifecycleOwner, onForegroundChange: OnForegroundChange) {
        val mForegroundLifecycleObserver = ForegroundLifecycleObserver(onForegroundChange)
        owner.lifecycle.addObserver(mForegroundLifecycleObserver)
        foregroundChange.add(mForegroundLifecycleObserver)
    }

    private fun notifyForegroundChange() {
        foregroundChange.takeIf { it.size > 0 }?.forEach { kotlin.runCatching { it.onForegroundChange(isForeground) } }
    }
}

internal class ForegroundLifecycleObserver(private var onForegroundChange: OnForegroundChange? = null) : DefaultLifecycleObserver {
    fun onForegroundChange(isForeground: Boolean) = onForegroundChange?.invoke(isForeground)
    override fun onDestroy(owner: LifecycleOwner) {
        onForegroundChange = null
        ProcessLifecycleObserver.foregroundChange.remove(this)
    }
}